package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"post/cache"
	"post/models"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	auto := c.PostForm("auto")

	if title == "" || auto == "" {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	post := models.Post{
		Title: title,
		Auto:  auto,
	}

	key := "add" + strconv.Itoa(int(post.ID))
	cache.Rdb.Get(cache.Ctx, key)

	models.DB.Create(&post)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func List(c *gin.Context) {
	var post []models.Post

	list := "list"
	key, _ := cache.Rdb.Get(cache.Ctx, list).Result()
	if key == "" {
		jsonData, _ := json.Marshal(&post)
		cache.Rdb.Set(cache.Ctx, key, jsonData, 5)
	} else {
		json.Unmarshal([]byte(key), &post)
	}

	err := models.DB.Find(&post).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": post,
	})
	return
}

func Del(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	del := "add" + strconv.Itoa(int(id))
	cache.Rdb.Del(cache.Ctx, del)

	err := models.DB.Where("id=?", id).Delete(&models.Post{}).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
		return
	}
}
